<?php
namespace app\common\model\food;

use app\common\model\BaseModel;
use Endroid\QrCode\QrCode as CodeMode;
use Endroid\QrCode\Writer\PngWriter;

/**
 * 二维码模型
 */
class Qrcode extends BaseModel
{
    // 定义表名
    protected $name = 'food_qrcode';
    
    // 定义主键
    protected $pk = 'qrcode_id';
    
    // 追加字段
    protected $append = [];

    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }
    
    /**
     * 关联餐桌表
     */
    public function table()
    {
        return $this->belongsTo('app\\common\\model\\food\\Table','table_id');
    }
    
    /**
     * 二维码类型
     */
    public function getTypeAttr($value)
    {
        $status = [10 => '小程序码', 20 => '门店码', 30 => '餐桌码', 40 => 'WIFI码'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取列表
     */
    public function getList($shop_id = 0)
    {
        //筛选条件
        $filter = [];
        $shop_id > 0 && $filter['shop_id'] = $shop_id;
        // 执行查询
        return $this->with(['shop','table'])
            ->where($filter)
            ->order(['qrcode_id' => 'desc'])
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }
    
    /**
     * 获取详情
     */
    public static function detail($id)
    {
        return self::with(['shop','table'])->find($id);
    }

    /**
     * 添加
     */
    public function add($data)
    {
        if(!file_exists('./qrcode/food')){
            mkdir('./qrcode/food',0777,true);
        }
        for($n=0;$n<$data['n'];$n++){
            //添加数据库记录
            $model = $this->create([
                'applet_id' => self::$applet_id
            ]);
            //生成二维码
            $writer = new PngWriter();
            $qrCode = CodeMode::create(base_url() . 'food/sn-' . $model->qrcode_id)
                ->setSize(500);
            $result = $writer->write($qrCode);
            $result->saveToFile('./qrcode/food/' . $model->qrcode_id . '.png');
        }
        return true;
    }

    /**
     * 编辑
     */
    public function edit(array $data)
    {
        if($data['type'] == 10){
           $data['shop_id'] = 0; 
           $data['table_id'] = 0;
        }
        if($data['type'] == 20 or $data['type'] == 40){
           $data['table_id'] = 0;
        }
        return $this->save($data) !== false;
    }

    /**
     * 删除
     */
    public function remove()
    {
        @unlink('./qrcode/food/' . $this->qrcode_id . '.png');
        return $this->delete();
    }
    
}

